package com.magic.auth;

import org.apache.commons.codec.digest.DigestUtils;

import com.magic.redis.jedis.JedisService;
import com.magic.util.SpringUtil;

/**
 * ClassName: JWTUtil <br/>
 * Function: token. <br/>
 * date: 2018年10月16日 下午12:09:43 <br/>
 * 
 * @author lishuai11
 * @version
 * @since JDK 1.8
 */
public class TokenUtil {

	private final static String SecretKey = "lanmeikeji:";// 私钥

	private final static int TOKEN_EXP = 60 * 60 * 24 * 30;// 过期时间

	public static String getToken(int userId) throws Exception {
		String token = DigestUtils.md5Hex(SecretKey + userId);
		JedisService jedisService = SpringUtil.getBean("jedisService");
		jedisService.setex(token, TOKEN_EXP, String.valueOf(userId));
		return token;
	}

	public static boolean checkToken(String token) throws Exception {
		JedisService jedisService = SpringUtil.getBean("jedisService");
		if (!jedisService.isExist(token)) {
			return false;
		} else {
			return true;
		}
	}

	public static void delToken(String token) throws Exception {
		JedisService jedisService = SpringUtil.getBean("jedisService");
		if (jedisService.isExist(token)) {
			jedisService.delete(token);
		}
	}

	public static boolean resourceAudit(String token, int userId) throws Exception {
		if (token.equals(getToken(userId))) {
			return true;
		} else {
			return false;
		}
	}

}
